<template>
  <div class="task-container">
    <div class="task-handle">
      <el-dropdown placement="bottom-start" @command="createTask">
        <el-button size="small" type="primary">新建</el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="self">自定义任务</el-dropdown-item>
          <el-dropdown-item command="temp">模板任务</el-dropdown-item>
          <el-dropdown-item divided command="newTeam">新建任务组</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button size="small" @click="refreshTaskList">刷新</el-button>
    </div>
    <el-form :inline="true" label-width="70" size="small">
      <el-form-item label="任务名称">
        <el-input v-model="searchInfo.name" placeholder="请填写任务名称" />
      </el-form-item>
      <el-form-item label="任务组">
        <el-select v-model="searchInfo.groupId">
          <el-option label="全部" value="" />
          <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="采集状态">
        <el-select v-model="searchInfo.status">
          <el-option label="全部" value="" />
          <el-option label="已完成" value="4" />
          <el-option label="周期任务暂停状态" value="3" />
          <el-option label="采集中" value="1" />
          <el-option label="未开始" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务类型">
        <el-select v-model="searchInfo.taskKind">
          <el-option label="全部" value="" />
          <el-option label="自定义任务" value="1" />
          <el-option label="模板任务" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getTaskList()">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="taskList" border max-height="400" :stripe="true">
      <el-table-column label="任务名" prop="name" />
      <el-table-column label="采集状态" prop="status" :formatter="stateFormatter" />
      <el-table-column label="任务组" prop="groupName" />
      <el-table-column label="编辑时间" prop="modifyDate" :formatter="dateFormatter" />
      <el-table-column label="操作" width="350">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 0" type="primary" size="small" @click="startTask(scope)">启动</el-button>
          <el-button v-if="scope.row.status !== 4 && scope.row.status !== 0" type="danger" size="small" @click="stopTask(scope)">终止</el-button>
          <el-dropdown placement="bottom-start" split-button size="small" type="primary" @command="handleTask($event,scope)">
            任务
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="edit">编辑</el-dropdown-item>
              <el-dropdown-item command="set">设置</el-dropdown-item>
              <el-dropdown-item command="delete">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="primary" size="small" @click="seeTaskData(scope)">查看数据</el-button>
          <!-- <el-button type="primary" size="small" @click="copyTask(scope)">复制</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:10px;text-align:center;">
      <el-pagination
        :current-page="pageInfo.page"
        :page-sizes="[ 20, 30, 40,50]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新建/编辑任务 -->
    <el-dialog :visible.sync="taskFlag" :title="handleTaskInfoTtile" @close="resetFields">
      <el-form ref="taskInfo" :model="taskInfo" :rules="infoRules" label-width="90px" size="small">
        <el-form-item label="任务分组" prop="groupId">
          <el-select v-model="taskInfo.groupId">
            <el-option v-for="item in groupList" :key="item.id" :label="item.name" :value="item.id.toString()" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务名" prop="name">
          <el-input v-model="taskInfo.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="字段模板" prop="modelId">
          <el-select v-model="taskInfo.modelId" placeholder="请选择字段模板">
            <el-option v-for="field in fieldModelList" :key="field.id" :label="field.name" :value="field.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="网站名称" prop="sourceName">
          <el-input v-model="taskInfo.sourceName" placeholder="请输入采集网站名称" />
        </el-form-item>
        <el-form-item label="采集网址" prop="sourceNet">
          <el-input v-model="taskInfo.sourceNet" placeholder="请输入采集网址" type="textarea" />
        </el-form-item>
        <el-form-item label="采集频率" prop="dispatch.period.type">
          <el-radio-group v-model="taskInfo.dispatch.period.type">
            <el-radio label="one">单次采集</el-radio>
            <el-radio label="day">每天采集</el-radio>
            <el-radio label="week">每周采集</el-radio>
            <el-radio label="month">每月采集</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启动时间" prop="dispatch.start">
          <el-date-picker v-model="taskInfo.dispatch.start" type="datetime" placeholder="选择日期时间" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="goSet('taskInfo')">确定</el-button>
        <el-button @click="cancelCreate('taskInfo')">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { PROJECT_API, GROUP_API, MODEL_API } from '@/api/index'
import { getFormartDate } from '@/utils/tools'
export default {
  name: 'Index',
  data() {
    const validateUrl = (rule, value, callback) => {
    //   const urlRegx = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/
      const urlRegx = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/|www\.)/
      if (value === '') {
        callback(new Error('请输入网址'))
      } else if (!urlRegx.test(value)) {
        callback(new Error('请填写正确的网址'))
      } else {
        callback()
      }
    }
    return {
      searchInfo: {
        name: '',
        groupId: '',
        status: '',
        taskKind: ''
      },
      taskList: [],
      groupList: [],
      pageInfo: {
        pageNo: 1,
        pageSize: 20
      },
      total: 0,
      taskFlag: false, // 任务操作框
      handleTaskInfoType: 0,
      taskInfo: {
        groupId: '', // 所属分组ID
        modelId: '', // 如果为模板任务，此为选用模板ID
        name: '',
        sys: 2, // 1系统模板  2自定义
        sourceNet: '',
        sourceName: '',
        config: '', // 采集配置信息
        increment: '', // 增量爬取配置信息
        dispatch: {
          start: '',
          period: {
            type: 'one',
            value: 1
          }
        }
      },
      infoRules: {
        groupId: [{ required: true }],
        name: [{ required: true, message: '请填写任务名称', trigger: 'blur' }],
        sourceName: [{ required: true, message: '请填写采集网站名称', trigger: 'blur' }],
        sourceNet: [{ required: true, validator: validateUrl, trigger: 'blur' }],
        modelId: [{ required: true, message: '请选择字段模板', trigger: 'change' }],
        'dispatch.start': [{ required: true, message: '请选择采集时间', trigger: 'change' }],
        'dispatch.period.type': [{ required: true }]
      },
      fieldModelList: [],
      loading: false
    }
  },
  computed: {
    handleTaskInfoTtile() {
      if (this.handleTaskInfoType === 0) {
        return '新建任务'
      } else {
        return '编辑任务'
      }
    }
  },
  mounted() {
    this.getTaskList()
    this.getGroupList()
    this.getFieldModels()
  },
  methods: {
    // 时间格式化
    dateFormatter(row, col, cellValue) {
      return getFormartDate(cellValue)
    },
    getFieldModels() { // 获取字段模板
      MODEL_API.modelList().then(res => {
        this.fieldModelList = res.data
      })
    },
    // 任务状态格式化
    stateFormatter(row, col, cellValue) {
      let state = ''
      switch (cellValue) {
        case 1:
          state = '采集中'
          break
        case 2:
          state = '运行队列中'
          break
        case 3:
          state = '周期任务队列中'
          break
        case 4:
          state = '已完成'
          break
        default :
          state = '未开始'
      }
      return state
    },
    getTaskList() { // 获取任务列表
      const info = _.cloneDeep(this.pageInfo)
      if (this.searchInfo.name) {
        info.name = this.searchInfo.name
      }
      PROJECT_API.getProjectList(info).then(res => {
        this.total = res.data.totalRows
        this.taskList = res.data.data
      }).catch(() => {})
    },
    // 获取任务组
    getGroupList() {
      GROUP_API.getGroupList({ pageSize: -1 }).then(res => {
        this.groupList = res.data.data
      }).catch(() => {})
    },
    // 刷新列表，重新获取数据
    refreshTaskList() {
      this.getTaskList()
    },
    //   分页显示条数改变
    handleSizeChange(size) {
      this.pageInfo.pageSize = size
      this.getProjectList()
    },
    // 页码改变
    handleCurrentChange(page) {
      this.pageInfo.pageNo = page
      this.getProjectList()
    },
    // 新建任务
    createTask(command) {
      if (command === 'self') {
        this.handleTaskInfoType = 0
        this.taskFlag = true
      } else if (command === 'temp') {
        this.$router.push('/module/module')
      } else {
        this.$router.push({
          path: '/taskTeam/teamList'
        })
      }
    },
    // 设置
    goSet(name) {
      this.$refs[name].validate((valid) => {
        if (valid === true) {
          if (this.handleTaskInfoType === 0) {
            const info = _.cloneDeep(this.taskInfo)
            info.dispatch.start = getFormartDate(info.dispatch.start)
            PROJECT_API.createProject(info).then(res => {
              this.$message({ type: 'success', message: '新建成功', center: true })
              this.taskFlag = false
              this.getTaskList()
            }).catch(err => {
              console.log(err)
            })
          } else {
            PROJECT_API.editProject(this.taskInfo).then(res => {
              this.$message({ type: 'success', message: '编辑成功', center: true })
              this.taskFlag = false
              this.getTaskList()
            })
          }
        }
      })
    },
    resetFields() {
      this.taskInfo = {
        id: '',
        groupId: '', // 所属分组ID
        modelId: '', // 如果为模板任务，此为选用模板ID
        name: '',
        sys: 2, // 1系统模板  2自定义
        sourceNet: '',
        sourceName: '',
        config: '', // 采集配置信息
        increment: '', // 增量爬取配置信息
        dispatch: {
          start: '',
          period: {
            type: 'one',
            value: 1
          }
        }
      }
      this.$refs['taskInfo'].resetFields()
    },
    // 取消创建
    cancelCreate(name) {
      this.$refs[name].resetFields()
      this.taskFlag = false
    },
    // 开始任务采集
    startTask(scope) {
      if (_.isEmpty(scope.row.config)) {
        this.$message({ type: 'error', message: '采集配置为空，请前往设置', center: true })
        return false
      }
      this.loading = true
      this.$confirm('您确定开始采集吗？', '系统提示', { type: 'info' }).then(() => {
        PROJECT_API.startProject(scope.row.id).then(res => {
          this.$message({ type: 'success', message: '启动成功', center: true })
          this.loading = false
          this.taskList[scope.$index].status = 1
        })
      }).catch(() => {})
    },
    // 终止采集中任务
    stopTask(scope) {
      this.$confirm('您确定暂停采集吗？终止后下次将重新采集所有数据', '系统提示', { type: 'warning' }).then(() => {
        this.taskList[scope.$index].status = 4
      }).catch(() => {})
    },
    // 任务相关操作
    handleTask(command, scope) {
      if (command === 'edit') {
        this.handleTaskInfoType = 1
        if (Object.prototype.toString.call(scope.row.dispatch) === '[object String]') {
          scope.row.dispatch = JSON.parse(scope.row.dispatch)
        }
        this.taskInfo = scope.row
        this.taskFlag = true
      } else if (command === 'set') {
        this.$router.push({ path: '/setTask', query: { projectId: scope.row.id, modelId: scope.row.modelId }})
      } else {
        this.$confirm('您确定要删除此任务吗？', '系统提示', { type: 'warning' }).then(() => {
          PROJECT_API.deleteProject(scope.row.id).then(res => {
            this.$message({ type: 'success', message: '删除成功', center: true })
            this.getTaskList()
          })
        }).catch(() => {})
      }
    },
    // 查看任务采集数据
    seeTaskData(scope) {
      this.$router.push({
        path: '/gatherData/dataList'
      })
    },
    // 复制任务
    copyTask(scope) {
      this.$confirm('您确定要复制此任务吗？', '系统提示', { type: 'warning' }).then(() => {

      }).catch(() => {})
    }
  }

}
</script>

<style lang="scss" scoped>
.task {
    &-handle {
        margin-bottom: 15px;
    }
    &-text {
        font-size: 30px;
        line-height: 46px;
    }
}
</style>
